package com.touchstone.synchdata.configuration.datasource;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * @Description : MSSQL数据源配置
 * @Author : hunter
 * @Date: 2019-08-12 22:16
 * @Version: 1.0
 **/
@Configuration
@MapperScan(basePackages = "com.touchstone.synchdata.dao.mssql", sqlSessionTemplateRef  = "mssqlSqlSessionTemplate")
public class MSSQLDataSource {

    @Value("${spring.datasource.mssql.driver-class-name}")
    private String driverClassName;

    @Value("${spring.datasource.mssql.url}")
    private String url;

    @Value("${spring.datasource.mssql.username}")
    private String username;

    @Value("${spring.datasource.mssql.password}")
    private String password;

    @Bean(name = "mssqlDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.mssql")
    public DataSource dataSource() {
//        DruidDataSource dataSource = new DruidDataSource();
//        dataSource.setDriverClassName(this.driverClassName);
//        dataSource.setUrl(this.url);
//        dataSource.setUsername(this.username);
//        dataSource.setPassword(this.password);
        return  new DruidDataSource();
    }

    @Bean(name = "mssqlSqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory(@Qualifier("mssqlDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/mssql/*.xml"));
        return bean.getObject();
    }

    @Bean(name = "mssqlTransactionManager")
    public DataSourceTransactionManager transactionManager(@Qualifier("mssqlDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "mssqlSqlSessionTemplate")
    public SqlSessionTemplate sqlSessionTemplate(@Qualifier("mssqlSqlSessionFactory") SqlSessionFactory sqlSessionFactory)
            throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}
